//
//  LLPCaptureHelper.m
//  LLP
//
//  Created by Porcellio on 10/10/12.
//  Copyright (c) 2012 Porcellio. All rights reserved.
//

#import "LLPCaptureHelper.h"

@interface LLPCaptureHelper (Private)

- (void)setStillImageOutput;
- (void)setVideoOutput;

@end

@implementation LLPCaptureHelper

@synthesize delegate = _delegate;
@synthesize category = _category;
@synthesize session = _session;

- (id)initWithCategory:(LLPCaptureCategory)captureCategory {

    if(self = [super init]) {
    
        _category = captureCategory;
        
        _session = [[AVCaptureSession alloc] init];
        if(_category == LLPCaptureCategoryPhoto) {
        
            if([_session canSetSessionPreset:AVCaptureSessionPresetPhoto]) {
            
                [_session setSessionPreset:AVCaptureSessionPresetPhoto];
            }
        }
        
        // 获取背面摄像头的引用.
        NSArray *devices = [AVCaptureDevice devices];
        for (AVCaptureDevice *device in devices) {
            
            if([device hasMediaType:AVMediaTypeVideo]) {
                
                if([device position] == AVCaptureDevicePositionBack) {
                    
                    _camera = [device retain];
                }
            }
        }
        
        if([self isDeviceSupportFlash:_camera]) {
            
            if([_camera lockForConfiguration:nil])
                [_camera setFlashMode:AVCaptureFlashModeAuto];
        }
        
        // 创建捕捉输入源实例, 并添加到会话中.
        _inputDevice = [[AVCaptureDeviceInput alloc] initWithDevice:_camera error:nil];
        if(_inputDevice != nil) {
            
            if([_session canAddInput:_inputDevice]) {
                
                [_session addInput:_inputDevice];
            }else {
                
                NSLog(@"Add input device error!");
            }
        }
        
        // 创建输出源实例， 并添加到会话中.
        _outputDevice = [[AVCaptureStillImageOutput alloc] init];
        NSDictionary *outputSettings = @{ AVVideoCodecKey : AVVideoCodecJPEG};
        [(AVCaptureStillImageOutput *)_outputDevice setOutputSettings:outputSettings];
        if(_outputDevice != nil) {
            
            if([_session canAddOutput:_outputDevice]) {
                
                [_session addOutput:_outputDevice];
            }else {
                
                NSLog(@"Add output device error!");
            }
        }
        
        // 捕获链接.
        for (AVCaptureConnection *connection in _outputDevice.connections) {
            
            for (AVCaptureInputPort *port in [connection inputPorts]) {
                
                if ([[port mediaType] isEqual:AVMediaTypeVideo]) {
                    
                    _connection = [connection retain];
                    
                    break;
                }
            }
            
            if(_connection)
                break;
        }
    }
    
    return self;
}

+ (BOOL)canSupportCapture {

    NSArray *videoDevice = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    if(videoDevice.count > 0) {
    
        return YES;
    }
    
    return NO;
}

- (void)captureImage {

    [(AVCaptureStillImageOutput *)_outputDevice captureStillImageAsynchronouslyFromConnection:_connection
                                               completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
                                                   
                                                   NSData *imageData =[AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
                                                   
                                                   if(_delegate != nil && [_delegate respondsToSelector:@selector(didCaptureStillImage:)]) {
                                                   
                                                       [_delegate didCaptureStillImage:imageData];
                                                   }
                                               }];
}

- (BOOL)startCaptureVideo {

    return NO;
}

- (void)endCaptureVideo {

}

- (void)changeCameraPosition {
    
    NSArray *devices = [AVCaptureDevice devices];
    for (AVCaptureDevice *device in devices) {
        
        if([device hasMediaType:AVMediaTypeVideo]) {
            
            if(device.position != AVCaptureDevicePositionUnspecified && _camera.position != device.position) {
            
                [_camera release];
                _camera = [device retain];
                
                [_session removeInput:_inputDevice];
                _inputDevice = [[AVCaptureDeviceInput alloc] initWithDevice:_camera error:nil];
                if([_session canAddInput:_inputDevice]) {
                
                    [_session addInput:_inputDevice];
                }
                
                [_connection release];
                
                // 捕获链接.
                for (AVCaptureConnection *connection in _outputDevice.connections) {
                    
                    for (AVCaptureInputPort *port in [connection inputPorts]) {
                        
                        if ([[port mediaType] isEqual:AVMediaTypeVideo]) {
                            
                            _connection = [connection retain];
                            
                            break;
                        }
                    }
                    
                    if(_connection)
                        break;
                }
                
                if([self isDeviceSupportFlash:_camera]) {
                    
                    if([_camera lockForConfiguration:nil])
                        [_camera setFlashMode:AVCaptureFlashModeAuto];
                }
                
                if(_delegate != nil && [_delegate respondsToSelector:@selector(didChangeDevicePosition:)]) {
                
                    [_delegate didChangeDevicePosition:_camera];
                }
                
                break;
            }
        }
    }
}

- (BOOL)isDeviceSupportFlash:(AVCaptureDevice *)device {

    if([device hasFlash]) {
    
        if([device isFlashModeSupported:AVCaptureFlashModeAuto]) {
        
            return YES;
        }
    }else {
    
        return NO;
    }
    
    return NO;
}

- (void)dealloc {

    [_connection release];
    [_camera release];
    
    [super dealloc];
}

#pragma mark -
#pragma mark Private Methods.

- (void)setStillImageOutput {

}

- (void)setVideoOutput {

}

@end
